package pb

import (
	. "chess_platform/internal/common"
	"fmt"
	"github.com/astaxie/beego/orm"
)

//合伙人后台系统
func UserInfoById(uid int64, multiOrm ...orm.Ormer) (PbUser, error) {
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
			uid = ?
		LIMIT 1
		`, TablePbUser)
	o := NewOrm(multiOrm, DBChessPartner)
	var user PbUser
	err := o.Raw(sql, uid).QueryRow(&user)
	if CheckNoExist(err) {
		return user, nil
	}
	return user, err
}

//公司提成比例
func CompanyBonusById(uid int64, multiOrm ...orm.Ormer) (int64, error) {
	sql := fmt.Sprintf(`
		SELECT
			bonus_rate
		FROM
			%v
		WHERE
			uid = ?
		LIMIT 1
		`, TablePbUser)
	o := NewOrm(multiOrm, DBChessPartner)
	var bonus int64
	err := o.Raw(sql, uid).QueryRow(&bonus)
	return bonus, err
}

func UserInfoByName(name string, multiOrm ...orm.Ormer) (PbUser, error) {
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
			name = ?
		LIMIT 1
		`, TablePbUser)
	o := NewOrm(multiOrm, DBChessPartner)
	var user PbUser
	err := o.Raw(sql, name).QueryRow(&user)
	if CheckNoExist(err) {
		return user, nil
	}
	return user, err
}

//更新一级代理的开通代理的名额
func UpdateUserAgentNum(agentNum, uid int64, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessPartner)
	sql := fmt.Sprintf(`UPDATE %v SET agent_num = agent_num + %v WHERE uid = %v`, TablePbUser, agentNum, uid)
	result, err := o.Raw(sql).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

func UpdateUser(user map[string]interface{}, uid int64, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessPartner)
	condition := fmt.Sprintf(`uid = %v`, uid)
	values, sql := UpdateSql(TablePbUser, user, condition)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

//获取合伙人所有的下级代理
func ListLevelUser(p ListParams, groupId, uid, pid int64, multiOrm ...orm.Ormer) ([]orm.Params, int64, error) {
	o := NewOrm(multiOrm, DBChessPartner)
	limit := (p.PageIndex - 1) * p.PageSize
	where := fmt.Sprintf(" group_id = %v AND pid = %v AND status = %v", groupId, pid, FirstTopUpSuccess)
	if uid != 0 {
		where = where + fmt.Sprintf(" AND uid = %v ", uid)
	}
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
			%v
		LIMIT ?,?
	`, TablePfUser, where)
	var user []orm.Params
	_, err := o.Raw(sql, limit, p.PageSize).Values(&user)
	if CheckNoExist(err) {
		return user, 0, nil
	}
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v WHERE %v`, TablePfUser, where)
	var count int64
	o.Raw(sql).QueryRow(&count)
	return user, count, err
}
